; docformat = 'rst'
;
; NAME:
;   ncPut
;
; PURPOSE:
;   Put data into netCDF file
;
;+
; :Categories:
;   Model utilities
;
; :Params:
;   var : variable to put into netCDF file
;   varID : variable name that will be input to netCDF file
;   
; :Keywords:
;   FileName : full path of netCDF file (required)
;   Dimensions : (input, required if varID doesn't already exist in netCDF file) string array containing the 
;     dimension names that the variable will be written in
;   Attributes : (input, optional) attributes to associate with the variable. String array of the format:
;     ['attribute1_name', 'attribute1_value', 'attribute2_name', 'attribute2_value']
;
; :Examples:
;   Overwrite existing variable in netCDF file::
;     IDL> ncPut, variable, 'VAR_NAME', filename=fname
;   Write new variable to netCDF file with dimensions a, b::
;     IDL> ncPut, variable, 'VAR_NAME', filename=fname, dimensions=['a', 'b'], attributes=['long_name', 'variable_name']
;
; :History:
;   Written by: Matt Rigby, MIT, May 31st 2011
;
;-
pro mr_ncput, var, varID, filename=filename, dimensions=dimensions, attributes=attributes, $
      double=double, char=char, float=float, byte=byte, long=long, short=short

  compile_opt idl2, hidden

  ncf=ncdf_open(filename, /write)

    ncstruct=ncdf_inquire(ncf)
    
    if ncstruct.nvars gt 0 then begin
      varname=strarr(ncstruct.nvars)
      for vi=0, ncstruct.nvars-1 do begin
        vartemp=ncdf_varinq(ncf, vi)
        varname[vi]=vartemp.name
      Endfor
    endif else varname=''

    if (total(varname eq replicate(varID, n_elements(varname))) eq 0) or (ncstruct.nvars eq 0) then begin

      dimname=strarr(ncstruct.ndims)
      dimsize=intarr(ncstruct.ndims)
      for di=0, ncstruct.ndims-1 do begin
        ncdf_diminq, ncf, di, nametemp, sizetemp
        dimname[di]=nametemp
        dimsize[di]=sizetemp
      Endfor
        
      ndimensions=size(dimensions, /n_elements)
      if ndimensions ne size(var, /n_dimensions) gt 0. then begin
        print, "!DIMENSIONS DON'T AGREE!"
        stop
      Endif
      
      dimIDs=intarr(ndimensions)
      
      For di=0, ndimensions-1 do begin
        dimIDS[di]=where(dimname eq dimensions[di])
      endfor
  
      ncdf_control, ncf, /redef
      vid=ncdf_vardef(ncf, varID, dimIDS, double=double, char=char, float=float, byte=byte, long=long, short=short)
  
      if keyword_set(attributes) then begin
        for ai=0, n_elements(attributes)/2-1 do begin
          NCDF_ATTPUT, ncf, varID, attributes[2*ai], attributes[2*ai+1], /char
        Endfor
      Endif
      
      ncdf_control, ncf, /endef

    Endif

    ncdf_varput, ncf, varID, var
  
  ncdf_close, ncf

End